﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementInput : MonoBehaviour
{
    Animator Anima;
    Camera MainCamera;
    CharacterController CharaController;

    [Header("Movement Setting")]
    public float moveSpeed = 10f;
    public float allowPlayerRotation;
    public bool blockPlayerRotation;
    [Range(0, 5)]
    public float rotationSpeed = 0.1f;

    [Header("Animation Smoothing")]
    [Range(0, 1)]
    public float HorizontalAnimSmoothTime = 0.2f;
    [Range(0, 1)]
    public float VerticalAnimSmoothTime = 0.2f;
    [Range(0, 1)]
    public float StartAnimTime = 0.3f;
    [Range(0, 1)]
    public float StopAnimTime = 0.15f;

    public bool isGrounded;
    // Start is called before the first frame update
    void Start()
    {
        Anima = GetComponent<Animator>();
        MainCamera = Camera.main;
        CharaController = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void FixedUpdate()
    {
        InputMagnitude();
    }

    void InputMagnitude()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        float speed = new Vector2(horizontal, vertical).sqrMagnitude;

        if (speed > allowPlayerRotation)
        {
            PlayerMoveAndRotation(horizontal, vertical);
        }
        PlayAnima(vertical, horizontal);
    }

    private float moveOffset;
    void PlayAnima(float vertical, float horizontal)
    {
        bool isMoving = Mathf.Abs(vertical) > 0 || Mathf.Abs(horizontal) > 0;
        Anima.SetBool("isMove", isMoving);
        if (isMoving)
        {
            if (Mathf.Abs(vertical) > 0) moveOffset = Mathf.Min(10, moveOffset + 1f);
            else moveOffset = Mathf.Max(0, moveOffset - 1f);
        }
        else
        {
            moveOffset = Mathf.Max(0, moveOffset - 1f);
        }

        Anima.SetFloat("move_veco", moveOffset);
    }

    void PlayerMoveAndRotation(float horizontal, float vertical)
    {
        var camForward = MainCamera.transform.forward;
        var camRight = MainCamera.transform.right;

        camForward.y = 0f;
        camRight.y = 0f;

        camForward.Normalize();
        camRight.Normalize();

        var desiredMoveDirection = camForward * vertical + camRight * horizontal;

        if (!blockPlayerRotation)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(desiredMoveDirection), rotationSpeed);
            CharaController.Move(desiredMoveDirection * Time.deltaTime * moveSpeed);
        }
    }
}
